import api from './api'
const movieApi = {
	// 获取全部电影列表
	getMovieList: function () {
		return api.get('/movie/movieList').then(res => {
			res.data.data.forEach(x => {
				this.change(x)
			})
			return res.data.data
		})
	},
	// 获取推荐电影
	getRecommend: function () {
		return api.get('/index/recommend').then(res => {
			let movieItem
			// 切割 只需要6个展示即可
			movieItem = res.data.data.splice(0, 6)
			movieItem.forEach(x => {
				this.change(x)
			})
			return movieItem
		})
	},
	// 获取对应类型的电影
	getTagMovie: function (tag) {
		return api.post('/movie/movieList', { tag }).then(res => {
			res.data.data.forEach(x => {
				this.change(x)
			})
			return res.data.data
		})
	},
	// 获取对应电影id信息
	getMovieDetails: function (movie_id) {
		return api.get(`/movie/details/${movie_id}`).then(res => {
			return this.change(res.data.data)
		})
	},
	// 查询电影平均评分
	getAvgRate: function (id) {
		return api.get(`/movie/evaluate/${id}`).then(res => {
			return res.data.avg_evaluate
		})
	},
	// 用户查询对该电影的评分
	getUserRate: function (id) {
		return api.get(`/users/evaluate/user/${id}`).then(res => {
			if (res.data.find_evaluate[0]) {
				return res.data.find_evaluate[0].evaluate
			} else {
				return 0
			}
		})
	},
	// 查询电影评论
	getCommentList: function (id) {
		return api.get(`/movie/comment/${id}`).then(res => {
			return res.data.data || []
		})
	},
	// 用户设置电影评分
	setUserRate: function (movie_id, movie_name, evaluate) {
		return api
			.post(`/users/evaluate`, { movie_id, movie_name, evaluate })
			.then(() => {
				AMessage.success('操作成功!')
			})
	},
	// 用户收藏电影
	getIsFavoriteMovie: function (movie_id) {
		return api.get(`/users/favorite/user/${movie_id}`).then(res => {
			return res.data
		})
	},
	// 用户收藏电影
	setFavoriteMovie: function (movie_id, movie_name) {
		return api
			.post(`/users/favorite`, { movie_id, movie_name })
			.then(res => {
				AMessage.success('收藏成功!')
				return res.data.newFavorite._id
			})
	},
	// 用户删除收藏电影
	delFavoriteMovie: function (id) {
		return api.delete(`/users/favorite/${id}`).then(() => {
			AMessage.success('取消成功!')
		})
	},
	// 用户提交电影评论
	setUserComment: function (movie_id, movie_name, context) {
		return api
			.post(`/users/movieComment`, { movie_name, movie_id, context })
			.then(res => {
				console.log(res)
				if (res.data.status === 0) {
					AMessage.success(res.data.message)
				} else {
					res.data.errors.forEach(x => {
						AMessage.error(x.msg)
					})
				}
			})
	},
	// 将数据格式化
	change: function (res) {
		res.movieCategory = res.movieCategory.split(',')
		res.movieTime = this.transformDate(res.movieTime)
		return res
	},
	transformDate: function (time) {
		return new Date(parseInt(time))
			.toLocaleString()
			.replace(/: \d{1,2}$/, ' ')
	}
}
export default movieApi
